#include <node.h>
#include "uvsc.hpp"

namespace UVCS
{

using v8::Exception;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Integer;
using v8::Object;
using v8::String;
using v8::Value;


void Init(const FunctionCallbackInfo<Value> &args){
    int uvMinPort, uvMaxPort;
    Isolate *isolate = args.GetIsolate();

    //数量检查
    if(args.Length() != 2){
        isolate->ThrowException(Exception::TypeError(
            String::NewFromUtf8Literal(isolate, "number of arguments should be TOW")));
            return;
    }

    //类型检查
    if(!args[0]->IsNumber() || !args[1]->IsNumber()){
        isolate->ThrowException(Exception::TypeError(
            String::NewFromUtf8Literal(isolate, "arguments type should be INTEGER")));
            return;
    }

    //读取
    uvMinPort = args[0].As<Integer>()->Value();
    uvMaxPort = args[1].As<Integer>()->Value();

    //有效性校验
    if(uvMinPort <  UVSC_MIN_AUTO_PORT | uvMaxPort >  UVSC_MAX_AUTO_PORT | uvMaxPort < uvMinPort | uvMaxPort - uvMinPort >= UVSC_MAX_CLIENTS){
        isolate->ThrowException(Exception::TypeError(
            String::NewFromUtf8Literal(isolate, "this port is out of rangge or invalid")));
            return;
    }

    UVSC_STATUS status = UVSC_Init(uvMinPort, uvMaxPort);

    Local<Integer> v8Status = Integer::New(isolate, status);

    args.GetReturnValue().Set(v8Status);
}


}